#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
int main(int argc, char** argv) {
	while(1){
		//读入
		char buffer[1000];
		printf( "Enter a instruction :");
		fgets(buffer, 1000, stdin);
		if(!strcmp(buffer,"quit\n")){		//输入指令quit
			break;						//跳出while循环
		}		
		//printf("Instructions input: %s\n", buffer);/*test*/
		//创建子进程
		int result;
		result = fork();
		if (result < 0) {
			perror("Failed to create child");
			exit(1);
		} else if (result == 0) {
			// Child 1
			
			//拆分指令
			char subprogram[100];			//程序名称长度不超过100个字符
			char subprogram_argv[64][100];	//参数数量不超过64个,每个参数字符数不超过100
			int index=0;
			int j=0;
			char temp[100];	
   			for(int i=0;i<strlen(buffer);i++){
   				if(buffer[i]==' ' || buffer[i]=='\t' || buffer[i]=='\n'){	//分句
   					temp[j]='\0';
   					if(index==0){			//第一子句是程序名称
   						strcpy(subprogram,temp);
   						//printf("subprogram is %s\n", subprogram);/*test*/
					}
					strcpy(subprogram_argv[index],temp);
   					index++;
   					j=0;
				}else if(j>=100){						//子句过长
					printf("Parameter %d too long!\n", index);
					exit(1);
				}else{
					temp[j]=buffer[i];
					j++;
				}
			}
			char *para[index+1];
			for(int i=0;i<index;i++){
				para[i]=subprogram_argv[i];	//获取需要执行的程序的参数
				//printf("%d: %s\n", i, para[i]);/*test*/
			}
			para[index]=NULL;
			
	
		printf("Child process's PID is %d. My parent's PID is %d.\n", getpid(), getppid());
		printf("Child process is about to execute \"%s\"\n\n", subprogram);
		result = execvp(subprogram, para);	//执行指定程序
		if (result == -1) {
			perror("In child process, failed to exec a program");
		}
		exit(1);
		} else {
			// parent
		int status;
		printf("Parent process's PID is %d.\n", getpid());	
		printf("Parent process is waiting ... \n");
		wait(&status);
		printf("In parent process, status = 0x%x, WEXITSTATUS(status) = %d (i.e. 0x%x)\n", \
		status, WEXITSTATUS(status), WEXITSTATUS(status));
		}
		//return (EXIT_SUCCESS);
		
		
	}
	
	printf("quit shell\n");
	return (EXIT_SUCCESS);	
}
